<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" :model="queryParams" layout="inline">
              <a-form-item label="菜单名称" name="menuName">
                <a-input v-model:value="queryParams.menuName" allow-clear  placeholder="请输入菜单名称"
                          @change="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="状态" name="status">
                <a-select v-model:value="queryParams.status" allow-clear placeholder="菜单状态" @change="handleQuery"
                  :options="sys_normal_disable" :field-names="{label: 'label', value: 'value'}">
                  <template #option="{ label, value }">
                    <a-flex justify="space-between">
                      <span>{{ label }}</span>
                      <span style="color: #999">{{ value }}</span>
                    </a-flex>
                  </template>
                </a-select>
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                        @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                        @click="resetQuery">重置
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>
    <el-row :gutter="12">
      <el-col :span="8">
        <div ref="menuTreeRef" class="tree-main-content">
          <a-spin :spinning="loading" size="large">
            <a-card class="card-content my-tree" hoverable style="overflow-y: scroll "
                    v-bind:style="{height:`${tableHeight+15}px`}">
              <el-tree ref="menuTreeRef" :data="menuList" :expand-on-click-node="false"
                       :props="{ label: 'menuName', children: 'children' }"
                       accordion class="mt-2 "
                       highlight-current node-key="menuId" @node-click="handleCurrentNode">
                <template #default="scope">
                  <div class="w-100% flex justify-between items-center">
                    <div class="flex gap-2 items-center">
                      <svg-icon :color="scope.data.status==='0'?'var(--el-color-primary-light-3)':'#F56C6C'"
                                :icon-class="scope.data.icon" />
                      <el-text>{{ scope.data.menuName }}</el-text>
                    </div>
                    <div class="flex gap-2 items-center">
                      <dict-tag :options="sys_menu_type" :size="'small'" :value="scope.data.menuType" />
                     <a-badge :status="scope.data.status==='0'?'success':'error'" />
                    </div>
                  </div>
                </template>
              </el-tree>
            </a-card>
          </a-spin>
          <a-card hoverable>
            <div class="flex justify-between items-center">
              <el-tooltip content="新增" placement="top">
                <el-button v-hasPermi="['system:menu:add']" circle round icon="Plus" plain type="primary"
                           @click="handleAdd(currentNode)" />
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button v-has-permi="['system:menu:add']" :disabled="single" circle icon="Edit" plain type="success"
                           @click="handleUpdate()" />
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button v-hasPermi="['system:menu:remove']" :disabled="single" circle plain icon="Delete"
                           type="danger"
                           @click="handleDelete(currentNode)" />
              </el-tooltip>
              <el-tooltip content="隐藏搜索" placement="top">
                <el-button v-hasPermi="['system:menu:add']" circle icon="Search" plain type="warning"
                           @click="toggleSearch()" />
              </el-tooltip>
              <el-tooltip content="刷新" placement="top">
                <el-button circle icon="Refresh" plain type="info" @click="handleQuery" />
              </el-tooltip>
            </div>
          </a-card>
        </div>
      </el-col>
      <el-col :span="16">
        <a-card ref="cardRef" class="card-content" hoverable>
          <template #title>
            <el-row ref="headerRef" :gutter="10">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:notice:remove']" round plain :disabled="multiple" icon="Delete" type="danger"
                           @click="handleBatchDelete()">
                  删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" :columns="columns"
                             @query-table="getButtonList"></right-toolbar>
            </el-row>
          </template>
          <a-spin :spinning="tableLoading" size="large">
            <el-table
              ref="menuTableRef"
              :data="buttonList"
              :default-expand-all="isExpandAll" :height="tableHeight"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              row-key="menuId" @selection-change="handleSelectionChange"
            >
              <el-table-column v-if="columns[0].visible" :fixed="columns[0].fixed" align="center" type="selection"
                               min-width="55" />
              <el-table-column v-if="columns[1].visible" :fixed="columns[1].fixed" align="center" label="菜单编号"
                               min-width="200" prop="menuId" />
              <el-table-column v-if="columns[2].visible" :fixed="columns[2].fixed" :show-overflow-tooltip="true"
                               align="center" label="权限名称" min-width="160" prop="menuName" />
              <el-table-column v-if="columns[3].visible" :fixed="columns[3].fixed" align="center" label="菜单类型"
                               min-width="120" prop="menuType">
                <template #default="scope">
                  <dict-tag :options="sys_menu_type" :value="scope.row.menuType" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns[4].visible" :fixed="columns[4].fixed" align="center" label="图标"
                               min-width="100" prop="icon">
                <template #default="scope">
                  <svg-icon :icon-class="scope.row.icon" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns[5].visible" :fixed="columns[5].fixed" align="center" label="排序"
                               min-width="60" prop="orderNum"></el-table-column>
              <el-table-column v-if="columns[6].visible" :fixed="columns[6].fixed" :show-overflow-tooltip="true"
                               align="center"
                               label="权限标识"
                               min-width="250" prop="perms"></el-table-column>
              <el-table-column v-if="columns[7].visible" :fixed="columns[7].fixed" align="center" label="状态"
                               min-width="100" prop="status">
                <template #default="scope">
                  <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column v-if="columns[8].visible" :fixed="columns[8].fixed" align="center" label="创建时间"
                               min-width="200" prop="createTime">
                <template #default="scope">
                  <span>{{ scope.row.createTime }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作" width="130">
                <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button v-hasPermi="['system:menu:edit']" circle icon="Edit" plain type="success"
                               @click="handleUpdate(scope.row)" />
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button v-hasPermi="['system:menu:remove']" circle plain icon="Delete" type="danger"
                               @click="handleDelete(scope.row)" />
                  </el-tooltip>
                </template>
              </el-table-column>
              <template #empty>
                <a-empty />
              </template>
            </el-table>
          </a-spin>
        </a-card>
      </el-col>
    </el-row>


    <el-drawer v-model="drawer.visible" :title="drawer.title" append-to-bod close-on-click-modal destroy-on-close
               size="40%">
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="form.parentId"
                :data="menuOptions"
                :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
                check-strictly
                placeholder="选择上级菜单"
                value-key="menuId"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="24">
            <el-form-item label="菜单图标" prop="icon">
              <div class="flex justify-between w-100%">
                <!-- 图标选择器 -->
                <icon-select v-model="form.icon" style="width: 70%" />
                <a-button shape="circle" @click="form.icon = ''">
                  <template #icon>
                    <svg-icon icon-class="clear" style=" font-size: 18px" />
                  </template>
                </a-button>
              </div>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon> </el-tooltip
                  >是否外链
                </span>
              </template>
              <el-radio-group v-model="form.isFrame">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item prop="path">
              <template #label>
                <span>
                  <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                              placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  路由地址
                </span>
              </template>
              <el-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item prop="component">
              <template #label>
                <span>
                  <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  组件路径
                </span>
              </template>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'M'" :span="12">
            <el-form-item>
              <el-input v-model="form.perms" maxlength="100" placeholder="请输入权限标识" />
              <template #label>
                <span>
                  <el-tooltip content="控制器中定义的权限字符，如：@SaCheckPermission('system:user:list')"
                              placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  权限字符
                </span>
              </template>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item>
              <el-input v-model="form.queryParam" maxlength="255" placeholder="请输入路由参数" />
              <template #label>
                <span>
                  <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  路由参数
                </span>
              </template>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType === 'C'" :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  是否缓存
                </span>
              </template>
              <el-radio-group v-model="form.isCache">
                <el-radio label="0">缓存</el-radio>
                <el-radio label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  显示状态
                </span>
              </template>
              <el-radio-group v-model="form.visible">
                <el-radio v-for="dict in sys_show_hide" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  菜单状态
                </span>
              </template>
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" name="Menu" setup>
import { addMenu, batchDelMenu, delMenu, getMenu, listButton, listMenu, updateMenu } from '@/api/system/menu';
import { MenuForm, MenuQuery, MenuVO } from '@/api/system/menu/types';
import { MenuTypeEnum } from '@/enums/MenuTypeEnum';
import { useElTableHeight } from '@/utils/useElTableHeight';
import useSettingsStore from '@/store/modules/settings';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
/*计算表格高度*/
const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef]);

const ids = ref<Array<string | number>>([]);
const multiple = ref(true);

interface MenuOptionsType {
  menuId: number;
  menuName: string;
  children: MenuOptionsType[] | undefined;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  sys_show_hide,
  sys_normal_disable,
  sys_menu_type
} = toRefs<any>(proxy?.useDict('sys_show_hide', 'sys_normal_disable', 'sys_menu_type'));

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `多选`, visible: true, fixed: true, children: [] },
  { key: 1, label: `菜单编号`, visible: false, fixed: false, children: [] },
  { key: 2, label: `权限名称`, visible: true, fixed: false, children: [] },
  { key: 3, label: `菜单类型`, visible: true, fixed: false, children: [] },
  { key: 4, label: `图标`, visible: false, fixed: false, children: [] },
  { key: 5, label: `排序`, visible: true, fixed: false, children: [] },
  { key: 6, label: `权限标识`, visible: true, fixed: false, children: [] },
  { key: 7, label: `状态`, visible: true, fixed: true, children: [] },
  { key: 8, label: `创建时间`, visible: true, fixed: false, children: [] }
]);

const menuList = ref<MenuVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const menuOptions = ref<MenuOptionsType[]>([]);
const isExpandAll = ref(false);
const single = ref(true);

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

const queryFormRef = ref<ElFormInstance>();
const menuFormRef = ref<ElFormInstance>();
const initFormData = {
  path: '',
  menuId: undefined,
  parentId: 0,
  menuName: '',
  icon: '',
  menuType: MenuTypeEnum.M,
  orderNum: 1,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0'
};
const data = reactive<PageData<MenuForm, MenuQuery>>({
  form: { ...initFormData },
  queryParams: {
    menuName: undefined,
    status: undefined
  },
  rules: {
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }]
  }
});

const menuTableRef = ref<ElTableInstance>();
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
};
const { queryParams, form, rules } = toRefs<PageData<MenuForm, MenuQuery>>(data);

/** 多选框选中数据 */
const handleSelectionChange = (selection: MenuVO[]) => {
  ids.value = selection.map((item) => item.menuId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 查询菜单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMenu(queryParams.value);
  const data = proxy?.handleTree<MenuVO>(res.data, 'menuId');
  if (data) {
    menuList.value = data;
  }
  loading.value = false;
};
/*查询按钮列表*/
const tableLoading = ref(false);
const buttonList = ref();
const getButtonList = async () => {
  tableLoading.value = true;
  const res = await listButton({ parentId: currentNode.value.menuId });
  buttonList.value = res.data;
  tableLoading.value = false;
};
/*当前选中节点*/
const currentNode = ref<MenuVO>();
const handleCurrentNode = async (data) => {
  currentNode.value = data;
  single.value = false;
  await getButtonList();
};

/** 查询菜单下拉树结构 */
const getTreeselect = async () => {
  menuOptions.value = [];
  const response = await listMenu();
  const menu: MenuOptionsType = { menuId: 0, menuName: '主类目', children: [] };
  menu.children = proxy?.handleTree<MenuOptionsType>(response.data, 'menuId');
  menuOptions.value.push(menu);
};
/** 取消按钮 */
const cancel = () => {
  reset();
  drawer.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  menuFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 新增按钮操作 */
const handleAdd = (row?: MenuVO) => {
  reset();
  getTreeselect();
  row && row.menuId ? (form.value.parentId = row.menuId) : (form.value.parentId = 0);
  drawer.visible = true;
  drawer.title = '添加菜单';
};
/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(menuList.value, isExpandAll.value);
};
/** 展开/折叠所有 */
const toggleExpandAll = (data: MenuVO[], status: boolean) => {
  data.forEach((item: MenuVO) => {
    menuTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};
/** 修改按钮操作 */
const handleUpdate = async (row?: MenuVO) => {
  reset();
  await getTreeselect();
  const menuId = row?.menuId || currentNode.value.menuId;
  if (menuId) {
    const { data } = await getMenu(menuId);
    form.value = data;
  }
  drawer.visible = true;
  drawer.title = '修改菜单';
};
/** 提交按钮 */
const submitForm = () => {
  menuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.menuId ? await updateMenu(form.value) : await addMenu(form.value);
      proxy?.$modal.notifySuccess('操作成功');
      drawer.visible = false;
      await getList();
      await getButtonList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: MenuVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.menuName + '"的数据项?');
  await delMenu(row.menuId);
  await getList();
  proxy?.$modal.notifySuccess('删除成功');
};
/*批量删除操作*/
const handleBatchDelete = async (row?: MenuVO) => {
  const menuIds = row?.menuId || ids.value;
  await proxy?.$modal.confirm('是否确认删除菜单编号为"' + menuIds + '"的数据项？');
  await batchDelMenu(menuIds);
  await getButtonList();
  proxy?.$modal.notifySuccess('删除成功');
};
onMounted(() => {
  getList();
});
</script>
